<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="listQuery.name" placeholder="名字" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
            <appSelect v-model="listQuery.appId" placeholder="所属应用"></appSelect>
            <companySelect v-model="listQuery.company" placeholder="所属商户"></companySelect>
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                查询
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
                新增
            </el-button>
        </div>

        <el-table
            :key="tableKey"
            v-loading="listLoading"
            :data="list"
            border
            fit
            highlight-current-row
            style="width: 100%;"
            @sort-change="sortChange"
        >

            <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
                <template slot-scope="{row}">
                    <span>{{ row.id }}</span>
                </template>
            </el-table-column>
            <el-table-column label="商品名" width="200px" align="center">
              <template slot-scope="{row}">
                <span>{{ row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="品牌" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.brandName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="封面图片" width="200px" align="center">
              <template slot-scope="{row}">
                <img :src="row.pic" style="width: 80px;height: 50px"/>
              </template>
            </el-table-column>
            <el-table-column label="上架状态" width="200px" align="center">
              <template slot-scope="scope">
                <p>上架：
                  <el-switch
                    @change="handlePublishStatusChange(scope.$index, scope.row)"
                    :active-value="1"
                    :inactive-value="0"
                    v-model="scope.row.publishStatus">
                  </el-switch>
                </p>
              </template>
            </el-table-column>
            <el-table-column label="审核状态" width="200px" align="center">
              <template slot-scope="{row}">
                <span>{{ row.verifyStatus | verifyStatusFilter }}</span>
              </template>
            </el-table-column>
            <el-table-column label="分类" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.productCategoryParentName }} / {{row.productCategoryName}}</span>
                </template>
            </el-table-column>
            <el-table-column label="属性类别" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.productAttributeCategoryName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="销量" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.sale }}</span>
                </template>
            </el-table-column>
            <el-table-column label="价格" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.price }}</span>
                </template>
            </el-table-column>
            <el-table-column label="副标题" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.subTitle }}</span>
                </template>
            </el-table-column>
            <el-table-column label="所属商户" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.companyName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="所属应用" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.appName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.createTime }}</span>
                </template>
            </el-table-column>
            <el-table-column label="更新时间" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.updateTime }}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="{row,$index}">
                    <el-button type="primary" size="mini" @click="handleUpdate(row)">
                        编辑
                    </el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
          <el-card class="form-container" shadow="never">
            <el-steps :active="active" finish-status="success" align-center style="margin-bottom: 20px">
              <el-step title="填写商品信息"></el-step>
              <el-step title="填写价格库存"></el-step>
              <el-step title="填写商品属性"></el-step>
              <el-step title="填写图片信息"></el-step>
            </el-steps>

            <div :class="{show:showStatus[0]}" style="display: none">
              <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" class="formClass">
                <el-form-item label="品牌">
                  <brandSelect v-model="temp.brandId" />
                </el-form-item>
                <el-form-item label="商品分类">
                  <productCateSelect v-model="temp" placeholder="选择分类"></productCateSelect>
                </el-form-item>
                <el-form-item label="商品名">
                  <el-input v-model="temp.name" />
                </el-form-item>
                <el-form-item label="上架状态">
                  <el-switch
                    :active-value="1"
                    :inactive-value="0"
                    v-model="temp.publishStatus">
                  </el-switch>
                  <span style="position: absolute;left: 80px;font-size: small;font-weight: 300">{{temp.publishStatus == 0? '下架':'上架'}}</span>
                </el-form-item>
                <el-form-item label="副标题">
                  <el-input v-model="temp.subTitle" />
                </el-form-item>
                <el-form-item label="商品描述">
                  <el-input v-model="temp.description" type="textarea" rows="3"/>
                </el-form-item>


              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button disabled>
                  上一步
                </el-button>
                <el-button type="primary" @click="nextStep">
                  下一步
                </el-button>
              </div>
            </div>

            <div :class="{show:showStatus[1]}" style="display: none">
              <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" class="formClass">

                <el-form-item label="价格">
                  <el-input v-model="temp.price" />
                </el-form-item>
                <el-form-item label="促销价格">
                  <el-input v-model="temp.promotionPrice" />
                </el-form-item>
                <el-form-item label="会员价">
                  <el-input v-model="temp.hyPrice" />
                </el-form-item>
                <el-form-item label="库存">
                  <el-input v-model="temp.stock" />
                </el-form-item>
                <el-form-item label="库存预警值">
                  <el-input v-model="temp.lowStock" />
                </el-form-item>
                <el-form-item label="单位">
                  <el-input v-model="temp.unit" />
                </el-form-item>
                <el-form-item label="商品重量(克)">
                  <el-input v-model="temp.weight" />
                </el-form-item>


              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="preStep">
                  上一步
                </el-button>
                <el-button type="primary" @click="nextStep">
                  下一步
                </el-button>
              </div>
            </div>

            <div :class="{show:showStatus[2]}" style="display: none">
              <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" class="formClass">

                <el-form-item label="属性类别">
                  <productAttrCateSelect v-model="temp.productAttributeCategoryId" placeholder="选择分类" @trap="myClick"></productAttrCateSelect>
                </el-form-item>
                <el-form-item label="商品规格">
                    <el-card shadow="never" class="cardBg">
                        <div v-for="(productAttr,idx) in temp.selectProductAttr">
                          {{productAttr.name}}：
                          <el-checkbox-group v-if="productAttr.inputType===1" v-model="temp.selectProductAttr[idx].values">
                            <el-checkbox v-for="item in getInputListArr(productAttr.inputList)" :label="item" :key="item" class="littleMarginLeft" @change="handleChange(idx,temp.productAttributeCategoryId)"></el-checkbox>
                          </el-checkbox-group>
                          <div v-else style="display: flex;flex-flow: column">
                            <el-checkbox-group v-model="temp.selectProductAttr[idx].values">
                              <div v-for="(item,index) in temp.selectProductAttr[idx].options" style="display: flex;flex-flow: row; margin: 8px 25px 0 0" class="littleMarginLeft">
                                <el-checkbox :label="item.option" :key="item.option" style="margin-right: 8px" @change="handleChange(idx,temp.productAttributeCategoryId)"></el-checkbox>
                                 <div style="font-size: 10px; margin:0 5px;">
                                  价格:<el-input v-model="item.price" style="margin-right: 8px;width: 100px !important;margin:0 5px;" placeholder="价格"></el-input>
                                 </div>
                                 <div style="font-size: 10px;margin:0 5px;">
                                  运费:<el-input v-model="item.freight" style="margin-right: 8px;width: 100px !important;margin:0 5px;" placeholder="运费"></el-input>
                                 </div>
                                <el-button class="littleMarginLeft" type="text" @click="handleRemoveProductAttrValue(idx,index)">删除</el-button>
                              </div>
                            </el-checkbox-group>
                            <div style="display: flex;flex-flow: row;margin-top: 20px">
                              <el-input v-model="addProductAttrValue" style="width: 160px;margin-left: 10px" clearable></el-input>
                              <el-button class="littleMarginLeft" @click="handleAddProductAttrValue(idx)">增加</el-button>
                            </div>
                          </div>
                        </div>
                    </el-card>
                </el-form-item>
                <el-form-item label="产品服务">
                  <productServiceSelect v-model="temp.serviceIds"/>
                </el-form-item>
                <el-form-item label="详情信息：">
                  <el-tabs v-model="activeHtmlName" type="card">
                    <el-tab-pane label="移动端详情" name="mobile">
                      <tinymce v-if="dialogFormVisible" :width="595" :height="300" v-model="temp.detailMobileHtml"></tinymce>
                    </el-tab-pane>
                  </el-tabs>
                </el-form-item>

              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="preStep">
                  上一步
                </el-button>
                <el-button type="primary" @click="nextStep">
                  下一步
                </el-button>
              </div>
            </div>

            <div :class="{show:showStatus[3]}" style="display: none">
              <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" class="formClass">
                <el-form-item label="封面图片">
                  <SingleUpload v-model="temp.pic" width="380"/>
                </el-form-item>
                <el-form-item label="画册图片">
                  <multi-upload v-model="selectProductPics"/>
                </el-form-item>
                <el-form-item label="所属商户">
                  <company-select v-model="temp.company"></company-select>
                </el-form-item>
                <el-form-item label="所属应用">
                  <app-select v-model="temp.appId"></app-select>
                </el-form-item>

              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="preStep">
                  上一步
                </el-button>
                <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
                  确定
                </el-button>
              </div>
            </div>


          </el-card>

        </el-dialog>

    </div>
</template>

<script>
    import {
        productList,
        productCreate,
        productUpdate,
        productDelete
    } from '@/api/product'

    import {productAttributeList} from '@/api/productAttribute'

    import waves from '@/directive/waves'
    import Pagination from '@/components/Pagination'
    import appSelect from '@/views/app/components/appSelect'
    import companySelect from '@/views/app/components/companySelect'
    import productCateSelect from '@/views/business/components/productCateSelect'
    import productAttrCateSelect from '@/views/business/components/productAttrCateSelect'
    import brandSelect from '@/views/business/components/brandSelect'
    import productServiceSelect from '@/views/business/components/productServiceSelect'
    import SingleUpload from '@/components/Upload/singleUpload'
    import multiUpload from '@/components/Upload/multiUpload'
    import Tinymce from '@/components/Tinymce'

    const defaultListQuery = {
        page: 1,
        limit: 15,
        name: '',
        company: '',
        appId:'',
        sort: '+id'
    };

    const currentTemp = {
        id: undefined,
        brandId: undefined,
        productCategoryId: undefined,
        productCategoryParentId: undefined,
        productAttributeCategoryId: undefined,
        name: undefined,
        pic: undefined,
        deleteStatus: undefined,
        publishStatus: undefined,
        verifyStatus: undefined,
        sale: undefined,
        price: undefined,
        promotionPrice: undefined,
        hyPrice: undefined,
        subTitle: undefined,
        description: undefined,
        stock: undefined,
        lowStock: undefined,
        unit: undefined,
        weight: undefined,
        previewStatus: undefined,
        serviceIds: undefined,
        albumPics: undefined,
        detailDesc: undefined,
        detailHtml: undefined,
        detailMobileHtml: '',
        promotionStartTime: undefined,
        promotionEndTime: undefined,
        promotionPerLimit: undefined,
        promotionType: undefined,
        company: undefined,
        appId: undefined,
        createTime: undefined,
        updateTime: undefined,
    }

    export default {
        name: 'product',
        components: { Pagination, appSelect, companySelect, productCateSelect, productAttrCateSelect, brandSelect
          ,SingleUpload ,multiUpload, productServiceSelect, Tinymce
        },
        directives: { waves },
        filters: {
          verifyStatusFilter(value){
            if (!value || value === 0 | value === '') {
              return '未审核';
            } else if (value === 1) {
              return '审核通过';
            } else if (value === 2) {
              return '审核不通过';
            }
          },
          serviceIds(ids){
            var target = {
              1:'无忧退货',
              2:'快速退款',
              3:'免费包邮'
            }
            var tag = ''
            if(ids){
              ids.split(",").forEach(id=>{
                tag += target[id]
              })
            }
            return tag
          }
        },
        data() {
            // var name = (rule, value, callback) => {
            //   if (value === '') {
            //     callback(new Error('模拟后台校验，请输入用户名'));
            //   } else {
            //     callback();
            //   }
            // }
            return {
                tableKey: 0,
                list: null,
                total: 0,
                listLoading: true,
                listQuery: Object.assign({}, defaultListQuery),
                temp: Object.assign({}, currentTemp),
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '修改',
                    create: '新增'
                },
                rules: {
                    // name: [{ validator: name, trigger: 'blur' }]
                },
                activeHtmlName: 'mobile',
                showStatus: [true, false, false, false],
                active: 0,
                //可手动添加的商品属性
                addProductAttrValue: ''
            }
        },
        created() {
            this.getList()
        },
        computed: {
            //商品的主图和画册图片
            selectProductPics:{
              get:function () {
                let pics=[];
                if(this.temp.albumPics===undefined||this.temp.albumPics==null||this.temp.albumPics===''){
                  return pics;
                }
                let albumPics = this.temp.albumPics.split(',');
                for(let i=0;i<albumPics.length;i++){
                  pics.push(albumPics[i]);
                }
                return pics;
              },
              set:function (newValue) {
                if (newValue == null || newValue.length === 0) {
                  this.temp.albumPics = null;
                } else {
                  this.temp.albumPics = '';
                  for (let i = 0; i < newValue.length; i++) {
                    this.temp.albumPics += newValue[i];
                    if (i !== newValue.length - 1) {
                      this.temp.albumPics += ',';
                    }
                  }
                }
              }
            }
        },
        watch: {
          active(v) {
            this.showStatus = []
            this.showStatus.forEach(() =>{this.showStatus.push(false)})
            this.showStatus[v] = true
          }
        },
        methods: {
            getList() {
                this.listLoading = true
                productList(this.listQuery).then(response => {
                    this.list = response.data.content
                    this.total = parseInt(response.data.totalElements)

                    this.listLoading = false
                })
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            sortChange(data) {
                const { prop, order } = data
                if (prop === 'id') {
                    this.sortByID(order)
                }
            },
            sortByID(order) {
                if (order === 'ascending') {
                    this.listQuery.sort = '+id'
                } else {
                    this.listQuery.sort = '-id'
                }
                this.handleFilter()
            },
            resetTemp() {
                this.temp = Object.assign({}, currentTemp)
            },
            handleCreate() {
                this.active = 0
                this.resetTemp()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })

            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        productCreate(this.temp).then(() => {
                            this.list.unshift(this.temp)
                            this.dialogFormVisible = false
                            this.$notify({
                                title: '提示',
                                message: '操作成功',
                                type: 'success',
                                duration: 2000
                            })
                            this.getList()
                        })
                    }
                })
            },
            handleUpdate(row) {
                this.active = 0
                this.temp = Object.assign({}, row) // copy obj
                this.dialogStatus = 'update'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })

            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                      const tempData = Object.assign({}, this.temp)
                      tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
                      tempData.selectProductAttr = this.temp.selectProductAttr
                      productUpdate(tempData).then(() => {
                        const index = this.list.findIndex(v => v.id === this.temp.id)
                        this.list.splice(index, 1, this.temp)
                        this.dialogFormVisible = false
                        this.$notify({
                          title: '提示',
                          message: '操作成功',
                          type: 'success',
                          duration: 2000
                        })
                        this.getList()
                      })
                    }
                })
            },
            handleDelete(row, index) {
                const tempData = {};
                tempData.id = row.id;
                const that = this;
                this.$confirm('确认删除？', '系统提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    cancelButtonClass: 'btn-custom-cancel',
                    type: 'warning'
                }).then(function(){
                    productDelete(tempData).then(() => {
                        that.$notify({
                            title: '提示',
                            message: '操作成功',
                            type: 'success',
                            duration: 2000
                        })
                        that.getList()
                    })
                }).catch(function(){
                    // console.log("取消成功！");
                })
            },
            handlePublishStatusChange(index, row) {
              let ids = [];
              ids.push(row.id);
              console.log("更新上架")
              // this.updatePublishStatus(row.publishStatus, ids);
            },
            nextStep(){
                this.active++
            },
            preStep(){
                this.active--
            },
            myClick(v) {
              if(v != ''){
                var query = Object.assign({}, this.listQuery)
                query.productAttributeCategoryId = v
                query.limit = 10000
                query.productId = this.temp.id
                productAttributeList(query).then(res => {
                  this.$set(this.temp, 'selectProductAttr', res.data.content)

                  // for(var i=0;i<res.data.content.length;i++){
                  //   var item = res.data.content[i]
                  //   this.$set(this.temp.selectProductAttr, i, item)
                  //   // // //可以用 item.values = []
                  //   // // //可以用 this.selectProductAttr[i] = item
                  //   // // //但是，不用 this.$set 赋值的话 修改数组的值，不会更新绑定数据，响应页面的
                  //   // // this.$set(this.temp.selectProductAttr, i, item)
                  //   // this.$set(this.temp.selectProductAttr, i, item)
                  // }

                })

              }
            },
            getInputListArr(inputList) {
              return inputList.split(',');
            },
            handleAddProductAttrValue(idx) {
              let options = this.temp.selectProductAttr[idx].options
              if (this.addProductAttrValue == null || this.addProductAttrValue == '') {
                this.$message({
                  message: '属性值不能为空',
                  type: 'warning',
                  duration: 1000
                });
                return
              }
              if (options.indexOf(this.addProductAttrValue) !== -1) {
                this.$message({
                  message: '属性值不能重复',
                  type: 'warning',
                  duration: 1000
                });
                return;
              }
              var item = {}
              item.option = this.addProductAttrValue
              this.temp.selectProductAttr[idx].options.push(item);
              this.addProductAttrValue = null;
            },
            handleRemoveProductAttrValue(idx, index) {
              this.temp.selectProductAttr[idx].options.splice(index, 1)
            },
            handleChange(idx,productAttributeCategoryId){
            }
        }
    }
</script>

<style lang="scss" scoped>

  .el-input {
    width: 220px !important;
  }
  .el-textarea {
    width: 380px !important;
  }
  .show {
    display: block !important;
  }
  .formClass {
    margin-left:50px;
  }
</style>
